# -*- coding: utf-8 -*-
from datetime import datetime
from django.core.urlresolvers import reverse
from django.db import models
from main.models import Employee
import datetime as _date

class Repair(models.Model):
    start = models.DateField(verbose_name=u"Дата начала")
    end = models.DateField(verbose_name=u"Дата окончания")
    is_holiday = models.BooleanField(verbose_name=u"Праздничный")
    give_access = models.BooleanField(verbose_name=u"Дать доступ для редактирования")

    class Meta:
        verbose_name=u'Ремонт'
        verbose_name_plural = u'Ремонты'

    def __unicode__(self):
        return u'%s' % self.start

    def get_absolute_url(self):
        return reverse('repairs_detail', args=[self.pk])

    def get_dates(self):
        d = self.end-self.start
        date_lst = [ self.end - _date.timedelta(days=x) for x in range(0, d.days+1) ]
        return date_lst

    def get_dates_iso(self):
        d = self.end-self.start
        date_lst = [ (self.end - _date.timedelta(days=x)).isoformat() for x in range(0, d.days+1) ]
        return date_lst

class RepairWorkers(models.Model):
    repair = models.ForeignKey(Repair, verbose_name=u"Ремонт")
    employee = models.ForeignKey(Employee, verbose_name=u"Сотрудник")
    date = models.DateField(verbose_name=u"Дата" )
    compensation = models.ForeignKey('Compensation', verbose_name=u"Компенсация")

    class Meta:
        verbose_name=u'Участник ремонта'
        verbose_name_plural = u'Участники ремонта'

    def __unicode__(self):
        return u'%s' % self.repair.start

    def save(self, *args, **kwargs):
        try:
            RepairWorkers.objects.get(repair=self.repair, employee=self.employee, date= self.date, compensation = self.compensation )
        except RepairWorkers.DoesNotExist:
            super(RepairWorkers, self).save(*args, **kwargs)


class Compensation(models.Model):
    title = models.CharField(max_length = 40, verbose_name=u"Название")

    class Meta:
        verbose_name=u'Компенсация'
        verbose_name_plural = u'Компенсации'

    def __unicode__(self):
        return u'%s' % self.title

    def get_workers(self):
       return self.repairworkers_set.values_list('employee',flat=True)

